package com.crazymakercircle.entity;

import com.crazymakercircle.constants.ServerConstants;
import com.crazymakercircle.util.JsonUtil;
import lombok.Data;

import java.io.Serializable;
import java.util.Objects;

/**
 * 工作节点的POJO类
 * create by 尼恩 @ 疯狂创客圈
 **/
@Data
public class WorkerData implements Serializable
{
    private static final long serialVersionUID = -499010884211304846L;

    //worker 的Id,zookeeper负责生成
    private String id;


    //工作节点 服务 IP
    private String host = "127.0.0.1";
    private String path = "un-known";


    public WorkerData()
    {
    }

    public WorkerData(String host)
    {
        this.host = host;
    }


    @Override
    public String toString()
    {
        return "WorkerData{" +
                "id='" + id + '\'' +
                "host='" + host + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        WorkerData node = (WorkerData) o;
//        return id == node.id &&
        return Objects.equals(host, node.host) &&
                Objects.equals(id, node.id);
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(id, host);
    }

    public static String getIdByPath(String path)
    {
        String sid = null;
        if (null == path)
        {
            throw new RuntimeException("节点路径有误");
        }
        int index = path.lastIndexOf(ServerConstants.PATH_WORKER_PREFIX);
        if (index >= 0)
        {
            index += ServerConstants.PATH_WORKER_PREFIX.length();
            sid = index <= path.length() ? path.substring(index) : null;
        }

        if (null == sid)
        {
            throw new RuntimeException("节点ID获取失败,path:" + path);
        }

        return sid;

    }

    public String toJson()
    {
        return JsonUtil.pojoToJson(this);
    }

    public static WorkerData fromJson(byte[] jsonBytes)
    {
        return JsonUtil.jsonBytes2Object(jsonBytes, WorkerData.class);
    }

}